package sk.vasicek.drinkmanager.activity;

import java.util.ArrayList;
import java.util.Locale;

import sk.vasicek.drinkmanager.R;
import sk.vasicek.drinkmanager.domain.DrinkEntry;
import sk.vasicek.drinkmanager.domain.Drinker;
import sk.vasicek.drinkmanager.domain.Drinker.Sex;
import sk.vasicek.drinkmanager.domain.Language;
import sk.vasicek.drinkmanager.service.BackgroundAdapter;
import sk.vasicek.drinkmanager.service.DrinkHistoryHelper;
import sk.vasicek.drinkmanager.service.DrinkPlaceHelper;
import sk.vasicek.drinkmanager.service.DrinkStatService;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphView.GraphViewSeries;
import com.jjoe64.graphview.LineGraphView;

public class DrinkGraphActivity extends Activity {

	private static String TAG = "DrinkGraphActivity";

	// protected ImageButton overviewButton;
	// protected ImageButton profileButton;
	// protected ImageButton billingButton;
	// protected ImageButton contactsButton;
	// protected Button settingsButton;
	// protected ListView drinkPointList;
	// protected ArrayAdapter<String> adapter;
	// protected ArrayList<String> drinkPointsList;
	// protected HashMap<String, DrinkPoint> drinkPointsMap;

	protected DrinkPlaceHelper drinkDatabaseHelper;

	private float alcoholMassCoeficientBySex;

	private float bodyWeight;
	SharedPreferences prefs;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Configuration config = getBaseContext().getResources().getConfiguration();
		Locale locale = Language.getApplicationLanguage(this);
		Locale.setDefault(locale);
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
		setContentView(R.layout.drink_graphs);
		Log.d(TAG, "Started DrinkGraphActivity");
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		// draw sin curve

		BackgroundAdapter.updateBackgroundFromPrefs(prefs, this);

		int gender = Integer.parseInt(prefs.getString("Gender", "1"));
		switch (gender) {
		case 1:
			this.alcoholMassCoeficientBySex = 0.70f;
			break;
		case 2:
			this.alcoholMassCoeficientBySex = 0.60f;
			break;
		default:
			Log.d(TAG, "In alcoholMassCoeficientBySex loading had to take default value");
			this.alcoholMassCoeficientBySex = 0.70f;
			break;
		}
		Log.d(TAG, "alcoholMassCoeficientBySex = " + this.alcoholMassCoeficientBySex);
		this.bodyWeight = Float.parseFloat(prefs.getString("Weight", "75").replaceAll(",", "."));
		Log.d(TAG, "bodyWeight = " + this.bodyWeight);

		DrinkStatService statService = new DrinkStatService();
		DrinkHistoryHelper drinkHistoryHelper = new DrinkHistoryHelper(this);
		ArrayList<DrinkEntry> drinkEntries = drinkHistoryHelper.getAllDrinksFromHistory();

		ArrayList<String> timeLabels = new ArrayList<String>();
		Float[] data = statService.generateAlcoholConcentrationGraphInput(drinkEntries, new Drinker("", Sex.values()[gender - 1], bodyWeight), timeLabels);
		GraphViewData[] graphViewDatas = new GraphViewData[statService.dataSize];
		for (int i = 0; i < data.length; i++) {
			graphViewDatas[i] = new GraphViewData(i, data[/* (data.length - 1) - */i] * 1000d);
		}
		GraphView graphView = new LineGraphView(getApplicationContext(), "Drink Graphs");
		// add data
		graphView.addSeries(new GraphViewSeries(graphViewDatas));
		// set view port, start=2, size=40
		graphView.setViewPort(0, statService.dataSize);
		graphView.setScrollable(true);
		graphView.setManualYAxisBounds(3, 0);
		// optional - activate scaling / zooming
		graphView.setScalable(true);
//		if (timeLabels != null) {
//			String[] labels = {};
//			graphView.setHorizontalLabels(timeLabels.toArray(labels));
//		}
		LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
		layout.addView(graphView);

		// updateDrinkPoints();
		// this.drinkPointList.setOnItemClickListener(new OnItemClickListener()
		// {
		//
		// @Override
		// public void onItemClick(AdapterView<?> adapterView, View view, int
		// no, long arg3) {
		// // Toast toast = Toast.makeText(getApplicationContext(),
		// // "You picked " + contactPhoneList.get(no),
		// // Toast.LENGTH_SHORT);
		// // toast.show();
		// Intent intent = new Intent(getApplicationContext(),
		// DrinkMapDetailActivity.class);
		// DrinkPoint drinkPoint = drinkPointsMap.get(drinkPointsList.get(no));
		// if (drinkPoint.getId() != null) {
		// intent.putExtra(DrinkPoint.POINT_ID, drinkPoint.getId());
		// }
		// if (drinkPoint.getTitle() != null &&
		// !"".equals(drinkPoint.getTitle())) {
		// intent.putExtra(DrinkPoint.POINT_TITLE, drinkPoint.getTitle());
		// }
		// if (drinkPoint.getSnippet() != null &&
		// !"".equals(drinkPoint.getSnippet())) {
		// intent.putExtra(DrinkPoint.POINT_SNIPPET, drinkPoint.getSnippet());
		// }
		// if (drinkPoint.getLatitude() != 0d) {
		// intent.putExtra(DrinkPoint.POINT_LATITUDE, drinkPoint.getLatitude());
		// }
		// if (drinkPoint.getLongitude() != 0d) {
		// intent.putExtra(DrinkPoint.POINT_LONGITUDE,
		// drinkPoint.getLongitude());
		// }
		// startActivity(intent);
		// }
		//
		// });

	}

	// private void updateDrinkPoints() {
	// drinkPointsList = new ArrayList<String>();
	// drinkPointsMap = new HashMap<String, DrinkPoint>();
	//
	// ArrayList<DrinkPoint> drinkPoints = new ArrayList<DrinkPoint>();
	//
	// drinkDatabaseHelper = new DrinkDatabaseHelper(getApplicationContext());
	// if (drinkDatabaseHelper != null) {
	// drinkPoints = drinkDatabaseHelper.getAllDrinkPoints();
	// for (DrinkPoint drinkPoint : drinkPoints) {
	// drinkPointsMap.put(getResources().getString(R.string.placeNo)+" "+(drinkPoint.getId())+": "+drinkPoint.getTitle(),
	// drinkPoint);
	// drinkPointsList.add(getResources().getString(R.string.placeNo)+" "+(drinkPoint.getId())+": "+drinkPoint.getTitle());
	// }
	// }
	// this.drinkPointList = (ListView) findViewById(R.id.drinkPlaceList);
	// adapter = new ArrayAdapter<String>(getApplicationContext(),
	// R.layout.drink_list_item, drinkPointsList);
	// drinkPointList.setAdapter(adapter);
	// }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = this.getMenuInflater();
		inflater.inflate(R.menu.optionmenu, menu);
		MenuItem settings = menu.findItem(R.id.settings);
		settings.setIntent(new Intent(this, SettingsActivity.class));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit:
			DrinkGraphActivity.this.finish();
			return true;
		case R.id.settings:
			Intent settingsIntent = item.getIntent();
			this.startActivityForResult(settingsIntent, 0);
			return true;
		case android.R.id.home:
			// Toast.makeText(DrinkManagerListActivity.this.getApplicationContext(),
			// getResources().getText(R.string.alreadyToast),
			// Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(this, DrinkManagerListActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case R.id.drinks:
			Intent drinksIntent = new Intent(getApplicationContext(), DrinkManagerListActivity.class);
			this.startActivityForResult(drinksIntent, 0);
			return true;
		case R.id.places:
			Intent placesIntent = new Intent(getApplicationContext(), DrinkPlacesActivity.class);
			this.startActivityForResult(placesIntent, 0);
			return true;
		case R.id.custom:
			Intent customIntent = new Intent(this, CustomDrinksActivity.class);
			this.startActivityForResult(customIntent, 0);
			// Toast.makeText(getApplicationContext(),
			// getResources().getText(R.string.alreadyToast),
			// Toast.LENGTH_SHORT).show();
			return true;
		case R.id.history:
			Intent historyIntent = new Intent(this, DrinkHistoryActivity.class);
			this.startActivityForResult(historyIntent, 0);
			// Toast.makeText(getApplicationContext(),
			// getResources().getText(R.string.alreadyToast),
			// Toast.LENGTH_SHORT).show();
			return true;
		case R.id.graphs:
			// Intent graphsIntent = new Intent(this, DrinkGraphActivity.class);
			// this.startActivityForResult(graphsIntent, 0);
			Toast.makeText(getApplicationContext(), getResources().getText(R.string.alreadyToast), Toast.LENGTH_SHORT).show();
			return true;
		case R.id.back:
			Intent backIntent = new Intent(getApplicationContext(), BackgroundChooserActivity.class);
			this.startActivityForResult(backIntent, 0);
			return true;
		case R.id.map:
			Intent mapsIntent = new Intent(getApplicationContext(), MapsOverlayActivity.class);
			this.startActivityForResult(mapsIntent, 0);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onResume() {
		// updateDrinkPoints();
		super.onResume();
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		BackgroundAdapter.updateBackgroundFromPrefs(prefs, this);

	}
}
